package com.healthtop.common;
import org.jsoup.helper.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * * 椿熙堂信息研发部
 * Author: 道长 on 2016/12/14.
 */
public class HttpUtils {


    /**
     * 获取客户端IP<br>
     * 默认检测的Header：<br>
     * 1、X-Forwarded-For<br>
     * 2、X-Real-IP<br>
     * 3、Proxy-Client-IP<br>
     * 4、WL-Proxy-Client-IP<br>
     * otherHeaderNames参数用于自定义检测的Header
     *
     * @param request 请求对象
     * @param otherHeaderNames 其他自定义头文件
     * @return IP地址
     */
    public static String getClientIP(javax.servlet.http.HttpServletRequest request, String... otherHeaderNames) {
        String[] headers = new String[]{"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};
//        if(Collections.emptyList(otherHeaderNames)){
//            headers = CollectionUtil.addAll(headers, otherHeaderNames);
//        }
        String ip;
        for (String header : headers) {
            ip = request.getHeader(header);
            if(false == isUnknow(ip)){
                return getMultistageReverseProxyIp(ip);
            }
        }

        ip = request.getRemoteAddr();
        return getMultistageReverseProxyIp(ip);
    }

    /**
     *Function:获取客户端IP地址，针对Nginx等反代作处理
     */
    public static String getIP(HttpServletRequest request){
        String ip=request.getHeader("x-forwarded-for");
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("X-Real-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getRemoteAddr();
        }
        return ip;
    }




    /**
     * 从多级反向代理中获得第一个非unknown IP地址
     * @param ip 获得的IP地址
     * @return 第一个非unknown IP地址
     */
    public static String getMultistageReverseProxyIp(String ip){
        // 多级反向代理检测
        if (ip != null && ip.indexOf(",") > 0) {
            final String[] ips = ip.trim().split(",");
            for (String subIp : ips) {
                if(false == isUnknow(subIp)){
                    ip = subIp;
                    break;
                }
            }
        }
        return ip;
    }

    public static boolean isUnknow(String checkString) {
        return StringUtil.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
    }
    // ----------------------------------------------------------------------------------------- Private method start end
}

